"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.offerErrorMiddleware = void 0;
const defines_1 = require("../lib/defines");
const Classrooms_1 = require("../lib/Classrooms");
const socket_message_1 = require("../utils/socket_message");
const log4js_1 = require("log4js");
const utils_1 = require("../utils/utils");
const logger = (0, log4js_1.getLogger)('Offer Helper');
async function offerErrorMiddleware(app, io) {
    const { socket } = app.locals;
    const { userId, username } = socket.handshake.query;
    const owner = { userId, username };
    const offerError = (message) => (0, socket_message_1.errorMsg)(defines_1.RequestMethod.offer, message, { owner });
    socket.use(async (event, next) => {
        const [name, params, cb] = event;
        if (name === defines_1.RequestMethod.offer) {
            const { member, room } = params;
            logger.info(`params:(${username}) => `, (0, utils_1.stringify)(params));
            if (!room) {
                return cb && cb(offerError(`params: room ${JSON.stringify(room, null, 2)} must required!`));
            }
            if (!member) {
                return cb && cb(offerError(`params: member ${JSON.stringify(member, null, 2)} must required!`));
            }
            const classroom = Classrooms_1.Classrooms.get(room.classId);
            if (!classroom) {
                return cb && cb(offerError(`room: ${JSON.stringify(room, null, 2)} not found in rooms!`));
            }
            const __member = classroom.getMember(member.userId);
            if (!__member) {
                return cb && cb(offerError(`member: ${JSON.stringify(member, null, 2)} not found in room!`));
            }
        }
        next();
    });
}
exports.offerErrorMiddleware = offerErrorMiddleware;
